<template>
    <div>

        <el-card class="box-card">
            <el-row :gutter="20">
                <el-col :span="7">
                    <el-input
                            placeholder="请输入内容"
                            v-model="queryInfo.query"
                            clearable
                            @clear="getUserList"
                    >
                        <el-button
                                slot="append"
                                icon="el-icon-search"
                                @click="getUserList"
                        ></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogOpen"
                    >添加用户
                    </el-button
                    >
                </el-col>
            </el-row>

            <el-table :data="userList" border stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="username" label="姓名" width="180">
                </el-table-column>
                <el-table-column prop="email" label="邮箱" width="180">
                </el-table-column>
                <el-table-column prop="mobile" label="电话"></el-table-column>
                <el-table-column prop="role_name" label="角色"></el-table-column>
                <el-table-column prop="mg_state" label="状态">
                    <template slot-scope="scope">
                        <el-switch
                                v-model="scope.row.mg_state"
                                active-color="#13ce66"
                                inactive-color="#ff4949"
                                @change="userStateChanged(scope.row)"
                        >
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-tooltip
                                class="item"
                                effect="dark"
                                content="编辑用户"
                                placement="top"
                        >
                            <el-button type="primary"
                                       icon="el-icon-edit"
                                       @click="showEditDialog(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip
                                class="item"
                                effect="dark"
                                content="删除用户"
                                placement="top"
                        >
                            <el-button type="danger" icon="el-icon-delete" @click="delUser(scope.row.id)"></el-button>
                        </el-tooltip>
                        <el-tooltip
                                class="item"
                                effect="dark"
                                content="分配角色"
                                placement="top"

                        >
                            <el-button type="warning" icon="el-icon-setting"   @click="setRole(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页功能 -->

<!--            <el-pagination-->
<!--                    @size-change="handleSizeChange"-->
<!--                    @current-change="handleCurrentChange"-->
<!--                    :current-page="queryInfo.pagenum"-->
<!--                    :page-sizes="[2, 4, 6, 8]"-->
<!--                    :page-size="queryInfo.pagesize"-->
<!--                    layout="total, sizes, prev, pager, next, jumper"-->
<!--                    :total="total"-->
<!--            >-->
<!--            </el-pagination>-->
            <Pager :queryInfo="queryInfo" :total="total" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"></Pager>
        </el-card>

        <el-dialog :title="title" :visible.sync="adddialogVisible" width="50%" @close="addDialogClosed">
            <!-- 内容主题区域 -->
            <el-form
                    :model="addUserForm"
                    :rules="rules"
                    ref="ruleForm"
                    label-width="70px"
            >
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addUserForm.username" :disabled="disabled"></el-input>
                </el-form-item>

                <el-form-item v-if="isShow" label="密码" prop="password">
                    <el-input v-model="addUserForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addUserForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="addUserForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser"
        >确 定</el-button
        >
      </span>
        </el-dialog>
        <!--    分配角色-->

        <el-dialog
                title="分配角色"
                :visible.sync="editDialogVisible"
                width="30%"
                @close="setRoleDialogClosed"
        >
            <div>
                <p>当前的用户：{{userInfo.username}}</p>
                <p>当前的角色：{{userInfo.role_name}}</p>
                <p>
                    分配新角色：
                    <el-select v-model="selectedRoleId" placeholder="请选择">
                        <el-option
                                v-for="item in roleList"
                                :key="item.id"
                                :label="item.roleName"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </p>
            </div>
            <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
  </span>
        </el-dialog>
    </div>
</template>
<script>
    import Pager from '../Pager'
    export default {
        data() {
            //验证邮箱的规则
            var validateMail = (rule, value, callback) => {
                const regEmail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/
                if (regEmail.test(value)) {
                    return callback()
                }
                callback(new Error("请输入合法邮箱"))
            };
            //验证手机号的规则
            var validateMobile = (rule, value, callback) => {
                const regMobile = /^[1][3,4,5,7,8][0-9]{9}$/
                if (regMobile.test(value)) {
                    return callback()
                }
                callback(new Error("请输入合法手机号"))
            };

            return {
                selectedRoleId:null,
                disabled: false,
                editDialogVisible: false,
                queryInfo: {
                    query: "",
                    pagenum: 1, //当前页数
                    pagesize: 2,
                },

                userList: [],
                rules: {
                    username: [
                        {required: true, message: '请输入用户名', trigger: 'blur'},
                        {min: 3, max: 100, message: '用户名的长度在3-10个字符之间', trigger: 'blur'}
                    ],
                    password: [
                        {required: true, message: '请输入密码', trigger: 'blur'},
                        {min: 3, max: 100, message: '密码的长度在3-10个字符之间', trigger: 'blur'}
                    ],
                    email: [
                        {required: true, message: '请输入邮箱', trigger: 'blur'},
                        {validator: validateMail, trigger: 'blur'}
                    ],
                    mobile: [
                        {required: true, message: '请输入手机号', trigger: 'blur'},
                        {validator: validateMobile, trigger: 'blur'}
                    ],

                },
                //添加用户的表单数据
                addUserForm: {
                    id: null,
                    username: '',
                    password: '',
                    email: '',
                    mobile: ''
                },
                title: '添加用户',
                total: 0,
                adddialogVisible: false,
                isShow: true,
                //需要被分配角色的用户信息
                userInfo: {},
                roleList: []

            };
        },
        created() {
            this.getUserList();

        },
        methods: {
            //监听switch开关状态的改变
            async userStateChanged(user) {
                const {data: res} = await this.$http.put(
                    `/users/${user.id}/state/${user.mg_state}`
                );
                if (res.meta.status !== 200) {
                    users.mg_state = !user.mg_state;
                    this.$message.error("更新用户状态失败");
                } else {
                    this.$message.success("更新用户状态成功");
                }
            },
            //监听pagesize改变事件
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.queryInfo.pagesize = val;
                this.getUserList();
            },
            //监听页码值改变的事件
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.queryInfo.pagenum = val;
                this.getUserList();
            },
            async getUserList() {
                console.log(this.queryInfo)
                const {data: res} = await this.$http.get("users", {
                    params: this.queryInfo,
                });
                console.log(res);
                if (res.meta.status !== 200) {
                    this.$message.error("登录失败");
                } else {
                    this.userList = res.data.users;
                    console.log(this.userList);
                    this.total = res.data.total;
                }
            },
            //监听添加用户对话框打开事件
            addDialogOpen() {
                this.adddialogVisible = true
                this.isShow = true
                this.disabled = false
                this.title = "添加用户"
            },
            //监听添加用户对话框的关闭事件
            addDialogClosed() {
                this.$refs.ruleForm.resetFields()


            },
            //点击按钮添加新用户
            addUser() {
                this.$refs.ruleForm.validate(async valid => {
                    if (valid) {
                        if (this.addUserForm.id) {
                            console.log("修改用户")
                            //发起添加请求
                            const {data: res} = await this.$http.put('users/' + this.addUserForm.id, {
                                email: this.addUserForm.email,
                                mobile: this.addUserForm.mobile
                            });
                            if (res.meta.status !== 200) {
                                this.$message.error("修改失败")
                            } else {
                                this.$message.success("修改成功")
                                this.adddialogVisible = false
                                this.getUserList()
                            }
                        } else {
                            console.log("添加用户")
                            //发起添加请求
                            const {data: res} = await this.$http.post('users', this.addUserForm);
                            if (res.meta.status !== 201) {
                                this.$message.error("添加失败")
                            } else {
                                this.$message.success("添加成功")
                                this.adddialogVisible = false
                                this.getUserList()
                            }
                        }

                    }
                })
            },
            //展示编辑用户的对话框
            showEditDialog(user) {
                const obj = JSON.parse(JSON.stringify(user))

                this.addUserForm = obj
                this.adddialogVisible = !this.adddialogVisible
                this.disabled = !this.disabled
                if (this.title == '修改用户') {
                    this.title = "添加用户"
                } else {
                    this.title = '修改用户'
                }
                this.isShow = false
                console.log(this.addUserForm)
            },
            //删除用户
            delUser(id) {
                this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',

                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    const {data: res} = await this.$http.delete("/users/" + id);
                    if (res.meta.status !== 200) {
                        this.$message.error("删除失败")
                    } else {
                        this.$message.success("删除成功")
                        this.getUserList()
                    }
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //展示分配角色
            async setRole(row) {
                console.log(1)
                this.userInfo = row;
                //获取所有角色
                const {data: res} = await this.$http.get('roles');
                if (res.meta.status !== 200) {
                    this.$message.error("获取角色失败")
                } else {
                    this.roleList = res.data
                }
                this.editDialogVisible = true;


            },
            //点击按钮分配橘色
           async saveRoleInfo(){
                if(!this.selectedRoleId){
                    this.$message.error("请选择角色")
                }else{
                    const {data: res} = await  this.$http.put(`users/${this.userInfo.id}/role`, {rid: this.selectedRoleId});
                    if(res.meta.status!==200){
                        this.$message.error("更新角色失败")
                    }else{
                        this.$message.success("更新角色成功")
                        this.getUserList()
                        this.editDialogVisible=false
                    }
                }
            },
            //监听分配角色对话框的关闭事件
            setRoleDialogClosed(){
                this.selectedRoleId=''
                this.userInfo={};
            }
        },
        components:{
            Pager
        },

    };
</script>
<style lang="less" scoped>
    .box-card {
        width: 100%;
    }
</style>